import path from 'path';
import fs, { existsSync, readFileSync, writeFileSync } from 'fs';
import yaml from 'yamljs';
import { beforeStartBuild, afterBuildFinish } from '../build-custom/BuildCustom';
import { execSync } from 'child_process';
import { BasePlatform } from '../platforms/BasePlatform';
import { SupportPlatform, supportPlatform } from '../platforms/PlatformConfig';
import PackUtil from '../utils/PackUtil';

class _Pack {
    public configData: any;
    public curPackChannel: string = "";
    public projectDir: string = "";
    public isDebug: boolean = false;

    public curPlatform: BasePlatform = null!;
    public constructor() {

    }
    /**
     * 初始化必要参数
     * @param projectDir 项目目录
     * @param packChannel 打包渠道
     * @returns 
     */
    public init(projectDir: string, packChannel: string, isdebug: boolean = false, version?: string) {
        this.isDebug = isdebug;
        let configPath = path.join(projectDir, "settings", "pack.config.yml");
        console.log(`projectDir=${projectDir}`, `pack channel=${packChannel}`);
        if (!fs.existsSync(configPath)) {
            console.error(`config file does't exits：${configPath}`);
            return;
        }
        this.projectDir = projectDir;
        this.configData = yaml.parse(fs.readFileSync(configPath).toString());
        if (!supportPlatform[packChannel]) {
            console.error(`current channel ${packChannel} pack script does't extis, please confirm`);
            return;
        }
        this.checkCustomEngine();
        this.curPlatform = new supportPlatform[packChannel]();
        this.curPlatform.init({ channel: packChannel, configData: this.configData, isDebug: this.isDebug, projectDir, forceVersion: version });
        this.startBuild(packChannel);
    }

    public startBuild(packChannel: string) {
        this.curPlatform.startBuild();
    }

    /**
     * 检测是否有自定义引擎路径，有则修改local/settings.json下的配置
     */
    public checkCustomEngine() {
        if (this.configData.customJsEnginePath || this.configData.customCppEnginePath) {
            let configPath = path.join(this.projectDir, "local");
            let settingjsonpath = path.join(configPath, "settings.json");
            if (!existsSync(settingjsonpath)) {
                PackUtil.mkdirSync(configPath);//没有对应输出目录则创建目录
                let obj = {
                    "use-global-engine-setting": false,
                    "use-default-js-engine": !this.configData.customJsEnginePath,
                    "js-engine-path": this.configData.customJsEnginePath ? this.configData.customJsEnginePath : "",
                    "use-default-cpp-engine": !this.configData.customCppEnginePath,
                    "cpp-engine-path": this.configData.customCppEnginePath ? this.configData.customCppEnginePath : "",
                }
                writeFileSync(settingjsonpath, JSON.stringify(obj, null, "\t"), { encoding: 'utf-8' });
            } else {
                let configinfo = JSON.parse(readFileSync(settingjsonpath, { encoding: 'utf-8' }));
                configinfo["use-global-engine-setting"] = false;
                configinfo["use-default-js-engine"] = !this.configData.customJsEnginePath;
                configinfo["use-default-cpp-engine"] = !this.configData.customCppEnginePath;
                if (this.configData.customJsEnginePath)
                    configinfo["js-engine-path"] = this.configData.customJsEnginePath;
                if (this.configData.customCppEnginePath) {
                    configinfo["cpp-engine-path"] = this.configData.customJsEnginePath;
                }
            }
        }
    }
}

export const PackManager = new _Pack();